from rest_framework.views import APIView
from rest_framework.response import Response
from .sers import *
from django.core.mail import send_mail
from HYDH1912A.settings import EMAIL_HOST_USER, SECRET_KEY
from django.contrib.auth.hashers import check_password
import jwt
import datetime


# Create your views here.

# 注册页面
class RegisterView(APIView):
    def post(self, request):
        ser = RegisterSer(data=request.data)
        if ser.is_valid():
            user = ser.save()

            # 发送邮件去激活用户
            send_mail('注册信息激活', '恭喜您,注册成功', EMAIL_HOST_USER,
                      recipient_list=[request.data.get('email')],
                      html_message="H1912A班发来贺电:恭喜您注册成功,"
                                   "接下来请激活<a href='http://127.0.0.1:8021/userapp/active/?id={}'>""激活</a>"
                      .format(user.id))

            return Response({"msg": "注册成功", "status": 200})
        else:
            print(ser.errors)
            return Response({"msg": "注册失败", "status": 400})


class UserView(APIView):
    def get(self, request):
        username = request.GET.get("username")
        if User.objects.filter(username=username):
            return Response({"msg": "用户名已存在", "status": 400})
        else:
            return Response({"msg": "用户名可用", "status": 200})


class UserActiveView(APIView):
    def get(self, request):
        cid = request.GET.get("id")
        User.objects.filter(id=cid).update(status=2)
        return Response({"msg": "激活成功"})


class LoginView(APIView):
    def post(self, request):

        username = request.data.get('username')
        password = request.data.get('password')
        user = User.objects.filter(username=username).first()
        # 先验证用户名 在验证密码
        if user and check_password(password, user.password):
            # 登录成功以后，生成 jwt令牌 来作为我们的登录凭证
            payload = {
                # jwt给了一些 常见的jwt令牌 exp表示设置过去的时间
                'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=1),
                'uid': user.id,

            }
            token = jwt.encode(payload, SECRET_KEY)
            return Response({'msg': '登录成功', 'status': 200, 'token': token})
        else:
            return Response({'msg': '登录失败', 'status': 400})


class TestTokenView(APIView):

    def get(self, request):
        token = request.GET.get('token')
        print(token)
        # 对 token令牌进行解码
        try:
            data = jwt.decode(token, SECRET_KEY)
        except Exception as e:
            print(e)
            return Response({"msg": "没有登录或登录失效，请重新登陆"})
        uid = data.get('uid')
        name = User.objects.get(id=uid)
        return Response({'msg': '识别出%s登录' % name})
